print('#############递归函数，函数调用本身#############')
print('#############阶乘，使用递归实现#############')


def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)


print(factorial(5))
# 计算过程
# ==>5*factorial(4)
# ==>5*factorial(4)*factorial(3)
# ==>5*factorial(4)*factorial(3)*factorial(2)
# ==>5*factorial(4)*factorial(3)*factorial(2)*factorial(1)
print('#############（栈帧）尾递归优化的语言可以通过尾递归防止栈溢出，需要定义两个方法，避免函数里面调用函数#############')


def fact(num):
    return fact_sub(num, 1)


def fact_sub(num, product):
    if num == 1:
        return product
    else:
        return fact_sub(num - 1, num * product)


print(fact(5))
# 计算过程
# ==>fact_sub(5,1)
# ==>fact_sub(4,5*1)
# ==>fact_sub(3,5*4*1)
# ==>fact_sub(2,5*4*3*1)
# ==>fact_sub(1,5*4*3*2*1)
